//
//  LZDSocketTool.m
//  LeasingPlatform
//
//  Created by 鲁征东 on 2020/6/10.
//  Copyright © 2020 柒点云. All rights reserved.
//

#import "LZDSocketTool.h"
#import "AFNetworking.h"

NSString *const USER_ID = @"user_id";
NSString *const LOGIN_SUCCESS = @"LOGIN_SUCCESS";

@implementation LZDSocketTool

+(void)PostRegistWithParamer:(NSDictionary*)paramer Result:(void(^)(BaseModel*baseModel))result;
{
    [LZD_ServerManager postWithUrl:API_login_register Parameters:paramer Success:^(id  _Nonnull responseObject) {
        BaseModel *modle = [BaseModel mj_objectWithKeyValues:responseObject];

        if (result) {
            result(modle);
        }
        
    } Failure:^(NSError * _Nonnull error) {
        if (result) {
                   result(nil);
               }
        
    }];
    
    
}



+(void)GetLoginWithParamer:(NSDictionary*)paramer UserInfo:(void(^)(LZdUserModel *userM))result
{
    
    [LZD_ServerManager postWithUrl:API_login_passlogin Parameters:paramer Success:^(id  _Nonnull responseObject) {
        
        LZdUserModel *userM= nil;
                   
                   BaseModel *base = [BaseModel mj_objectWithKeyValues:responseObject];
                   if (base.code==1) {
                       userM = [LZdUserModel mj_objectWithKeyValues:base.data];

                       [[NSUserDefaults standardUserDefaults] setValue:userM.ID forKey:USER_ID];
                       [[NSUserDefaults standardUserDefaults] synchronize];
                       
                       
                      
                   }
               
               if (result) {
                   result(userM);
               }
        
    } Failure:^(NSError * _Nonnull error) {
        if (result) {
              result(nil);
         }
    }];
    
    
}

+(void)SearchUserWithParamer:(NSDictionary*)paramer Result:(void(^)(NSArray<XZGroup*>*userList))result{
    

    [LZD_ServerManager getDataGetWithUrl:API_index_searchUser Parameters:paramer Success:^(id  _Nonnull responseObject) {
        NSMutableArray *arr = [NSMutableArray array];

        BaseModel *bs = [BaseModel mj_objectWithKeyValues:responseObject];
        if (bs.code==1) {
            
            for (NSDictionary*dic in responseObject[@"data"]) {
                
                [arr addObject:[XZGroup mj_objectWithKeyValues:dic]];
            }
        }
        
        if (result) {
                   result(arr);
           }
        
    } Failure:^(NSError * _Nonnull error) {
        if (result) {
                   result(@[]);
        }
        
    }];
    
    
    
    
    
    
}

//获取会话列表
+(void)loadSessionListUserId:(NSString *)userId Result:(void(^)(NSArray<XZGroup*>*list))result{
    
    if ([userId isEmptyString] || userId==nil) {
        if (result) {
            result(@[]);
        }
        return;
    }
    
    [LZD_ServerManager getDataGetWithUrl:API_index_getFriend Parameters:@{@"user_id":userId} Success:^(id  _Nonnull responseObject) {
       
        NSMutableArray *arr = [NSMutableArray array];
        
            
            BaseModel *bs = [BaseModel mj_objectWithKeyValues:responseObject];
            if (bs.code==1) {
                
                for (NSDictionary*dic in responseObject[@"data"]) {
                    
                    [arr addObject:[XZGroup mj_objectWithKeyValues:dic]];
                }
            }
        
        
        if (result) {
            result(arr);
        }
    } Failure:^(NSError * _Nonnull error) {
        if (result) {
            result(@[]);
        }
    
    }];
    
    
    ;
       
    
    
    
}

//获取聊天记录
+(void)getChartRecords:(NSDictionary *)paramer Result:(void(^)(NSArray<ICMessage*>*list))result{
    
    
    
    [LZD_ServerManager getDataGetWithUrl:API_index_getMsg Parameters:paramer Success:^(id  _Nonnull responseObject) {
       
        NSMutableArray *arr = [NSMutableArray array];
        
            BaseModel *bs = [BaseModel mj_objectWithKeyValues:responseObject];
            if (bs.code==1) {
                
                for (NSDictionary*dic in responseObject[@"data"]) {
                    
                    [arr addObject:[ICMessage mj_objectWithKeyValues:dic]];
                }
            }
        
        
        if (result) {
            result(arr);
        }
    } Failure:^(NSError * _Nonnull error) {
        if (result) {
                   result(@[]);
               }
    }];
    
       
    
    
    
}


//发送消息
+(void)LZD_socketSendData:(NSDictionary*)dic{
    
//    LxDBAnyVar([dic jsonString]);
    
    [[SocketRocketUtility instance]sendData:[dic jsonString]];
    
}


///上传图片
+(void)UpLoadImage:(UIImage *)img Type:(NSString*)type Result:(void(^)(NSString *remoteFilePath))result{
    
    if (type.length==0 || type ==nil) {
        type = @"user_vatar";
    }
    
    
    [LZD_ServerManager uploadImageWithUrl:[BASE_URL stringByAppendingPathComponent:API_login_upload] Parameters:@{@"type":type} UploadImage:img Success:^(id  _Nonnull responseObject) {
        NSString *photoPath;
        if ([responseObject[@"code"] intValue]==1) {
                          photoPath = responseObject[@"data"][@"path"];
           }
        if (result) {
                   result(photoPath);
               }
        
    } Failure:^(NSError * _Nonnull error) {
        if (result) {
                   result(@"");
               }
    }];
    

    
    
}


///上传文件
+(void)UpLoadFile:(NSString *)filePath FileType:(NSString*)type Result:(void(^)(NSString *remoteFilePath))result{
    
    NSMutableDictionary *paramer = [NSMutableDictionary dictionary];
    if ([type isEqualToString:@"voice"]) {
        [paramer setValue:@"voice" forKey:@"type"];
    }else if ([type isEqualToString:@"video"]){
        [paramer setValue:@"video" forKey:@"type"];

        
    }else if ([type isEqualToString:@"img"]){
        [paramer setValue:@"img" forKey:@"type"];

        
    }
    
    
    [LZD_ServerManager uploadFileWithURL:[BASE_URL stringByAppendingPathComponent:API_login_upload] parameters:paramer name:@"file" filePath:[NSURL fileURLWithPath:filePath].absoluteString success:^(id  _Nonnull Json) {
        
        NSString *remoteFilePath;
        if ([Json[@"code"] intValue]==1) {
                 remoteFilePath = Json[@"data"][@"path"];
              }
        if (result) {
               result(remoteFilePath);
                      }
        
    } failure:^(id  _Nonnull json) {
        
        if (result) {
             result(@"");
          }
    }];
    

    

    
    
}




@end













static id _instance;
static NSMutableArray *_allSessionTask;
static NSString * _baseURL;

@implementation LZD_ServerManager

+ (AFHTTPSessionManager *)sharedHTTPSession {
    static dispatch_once_t onceToken;
    static AFHTTPSessionManager *manager;

    dispatch_once(&onceToken, ^{
        
        
        manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html", @"text/json", @"text/javascript",@"text/plain",@"var",nil];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
            AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
           [securityPolicy setAllowInvalidCertificates:YES];
           [manager setSecurityPolicy:securityPolicy];
        
        /* 请求队列最大并发数 */
        manager.operationQueue.maxConcurrentOperationCount = 5;
        /* 请求超时的时间 */
        manager.requestSerializer.timeoutInterval = 15;
    });
    return manager;
}
static AFNetworkReachabilityManager * networkManager ;
+ (AFNetworkReachabilityManager *)sharedNetworkManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        networkManager = [AFNetworkReachabilityManager manager];
        
    });
    return networkManager;
}

+ (void)setBaseURL:(NSString *)baseURL
{
    _baseURL = baseURL;
}





+ (void)getDataGetWithUrl: (NSString *)url Parameters:(id)parameter Success: (void (^) (id responseObject))success Failure: (void (^) (NSError *error))failure {
    AFHTTPSessionManager *Manager = [self sharedHTTPSession];
    
    /* 数据请求 */
    if (_baseURL.length) {
           url = [NSString stringWithFormat:@"%@%@",_baseURL,url];
       }
    
    NSURLSessionTask *sessionTask =  [Manager GET:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil;

    
}

+ (void)postWithUrl: (NSString *)url Parameters: (id)parameter Success: (void (^) (id responseObject))success Failure: (void (^) (NSError *error))failure {
    AFHTTPSessionManager *Manager = [self sharedHTTPSession];
    if (_baseURL.length) {
           url = [NSString stringWithFormat:@"%@%@",_baseURL,url];
       }
    NSLog(@"%@\n%@",url,parameter);
    
    
    NSURLSessionTask *sessionTask =  [Manager POST:url parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            
         
            success(responseObject);
          
            
        }
        
        [[self allSessionTask] removeObject:task];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [[self allSessionTask] removeObject:task];

        if (failure) {
            failure(error);
            NSLog(@"error---%@",error);
            if ([error.localizedDescription isEqualToString:@"已取消"]){
                
                
            }else{
                
            }
            
        }
    }];
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil;

}

+ (void)uploadImageWithUrl: (NSString *)url Parameters: (id)parameter UploadImage :(UIImage *)uploadImage Success: (void (^) (id responseObject))success Failure: (void (^) (NSError *error))failure {
    
    AFHTTPSessionManager *Manager = [self sharedHTTPSession];
   NSURLSessionTask *sessionTask =  [Manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (uploadImage != nil) {
            NSData *imgData = UIImageJPEGRepresentation(uploadImage, 0.5);
            [formData appendPartWithFileData:imgData name:@"file" fileName:@"photo" mimeType:@"image/png"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
        [[self allSessionTask] removeObject:task];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
        [[self allSessionTask] removeObject:task];

    }];
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil;

}

+ (void)monitoringNetStatus:(void (^)(id responseObject))netStatus {
    AFNetworkReachabilityManager * manager = [self sharedNetworkManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                if (netStatus) {
                    netStatus(@"未知网络类型");
                }
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
                if (netStatus) {
                    netStatus(@"无可用网络");
                }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                if (netStatus) {
                    netStatus(@"使用蜂窝流量");
                }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                if (netStatus) {
                    netStatus(@"当前WIFI下");
                }
                break;
                
            default:
                break;
        }
    }];
    [manager startMonitoring];
}
#pragma mark 上传多张图片
+ (void)uploadImageWithPath:(NSString *)path photos:(NSArray *)photos params:(NSDictionary *)params currentProgress:(progressBlock)currentProgress success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure
{
    
    AFHTTPSessionManager *manager = [self sharedHTTPSession];
   NSURLSessionTask *sessionTask =  [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < photos.count; i ++) {
            //            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            //            formatter.dateFormat=@"yyyyMMddHHmmss";
            //            NSString *str=[formatter stringFromDate:[NSDate date]];
            
            NSTimeInterval timeval = [[NSDate date]timeIntervalSince1970];
            
            NSString *fileName=[NSString stringWithFormat:@"%.0f.jpg",timeval*1000];
            UIImage *image = photos[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 1);
            //            NSLog(@"coverFile---%@  %@   %lf",[NSString stringWithFormat:@"coverFile%d",i+1],str,timeval);
            [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"coverFile%d",i+1] fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        currentProgress(uploadProgress);
        
        NSLog(@"uploadProgress is %lld,总字节 is %lld",uploadProgress.completedUnitCount,uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[self allSessionTask] removeObject:task];

        if (success){
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
         [[self allSessionTask] removeObject:task];
    }];
    
    
    //添加最新的sessionTask到数组
       sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil;
}


#pragma mark -- 上传文件
+ (void)uploadFileWithURL:(NSString *)url parameters:(NSDictionary *)parameters  name:(NSString *)name filePath:(NSString *)filePath success:(HttpUploadSuccessBlock)success failure:(HttpUploadFailureBlock)failure
{
    AFHTTPSessionManager *manager = [self sharedHTTPSession];
  NSURLSessionDataTask * sessionTask =  [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    
        //添加-文件
        NSError *error = nil;
        [formData appendPartWithFileURL:[NSURL URLWithString:filePath] name:name error:&error];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        dispatch_sync(dispatch_get_main_queue(), ^{
            
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [[self allSessionTask] removeObject:task];
        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [[self allSessionTask] removeObject:task];
        failure ? failure(error) : nil;
    }];
    //添加最新的sessionTask到数组
    sessionTask ? [[self allSessionTask] addObject:sessionTask] : nil;
}



#pragma mark -- 下载文件
+ (void)downloadWithURL:(NSString *)url fileDir:(NSString *)fileDir progress:(progressBlock)progress callback:(httpDownload)callback
{
    if (!fileDir.length) {
            LxDBAnyVar(@"下载路径为空，使用默认目录");
        NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        fileDir = [documents stringByAppendingPathComponent:@"HJDownloader"];
    }

    NSString *fileName = url.lastPathComponent;
    NSString *savePath = [fileDir stringByAppendingPathComponent:fileName];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:savePath];
    if (fileExists) {//文件已下载，直接返回
            LxDBAnyVar(@"文件已下载，直接返回");
        callback ? callback(savePath, nil) : nil;
        return;
    }
    
    BOOL folderExists = [fileManager fileExistsAtPath:fileDir];
    NSError *directoryCreateError = nil;
    if (!folderExists) {//文件夹不存在，创建目录
            LxDBAnyVar(@"文件夹不存在，创建目录");
        [fileManager createDirectoryAtPath:fileDir withIntermediateDirectories:YES attributes:nil error:&directoryCreateError];
    }
    if (directoryCreateError) {
        callback ? callback(nil, directoryCreateError) : nil;
        return;
    }

    //创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    //下载任务
    AFHTTPSessionManager *manager = [self sharedHTTPSession];

    __block NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        // 下载进度
//        if (_logEnabled) {
            LxPrintf(@"下载进度:%.2f%%",100.0*downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
//        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            progress ? progress(downloadProgress) : nil;
        });
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        // 设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象
        return [NSURL fileURLWithPath:savePath]; // 返回的是文件存放在本地沙盒的地址
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        // 下载完成调用的方法
        [[self allSessionTask] removeObject:downloadTask];
        if (callback && error) {
            callback ? callback(nil, error) : nil;
            return;
        }
        callback ? callback(filePath.absoluteString, nil) : nil;
    }];
    
    //启动下载任务
    [downloadTask resume];
    //添加sessionTask到数组
    downloadTask ? [[self allSessionTask] addObject:downloadTask] : nil;
}


/*取消指定URL的Http请求*/
+ (void)cancelRequestWithURL:(NSString *)url{
    if (!url) { return; }
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task.currentRequest.URL.absoluteString hasPrefix:url]) {
                [task cancel];
                [[self allSessionTask] removeObject:task];
                *stop = YES;
            }
        }];
    }
}



/*取消所有Http请求*/
+ (void)cancelAllRequest{
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self allSessionTask] removeAllObjects];
    }
}

/*所有的请求task数组*/
+ (NSMutableArray *)allSessionTask{
    if (!_allSessionTask) {
        _allSessionTask = [NSMutableArray array];
    }
    return _allSessionTask;
}

@end
